package com.hxy.manager.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.hxy.manager.entity.GoodsEntity;
import com.hxy.manager.util.Constant;
import com.hxy.manager.util.StringUtil;

import java.util.List;


public class SyncService extends Service {

    final String host = "182.254.227.30";//服务器地址
    final String port = "10086";
    final String version = "1.17.9";
    //实现一个INBinder接口
    public final IBinder myBinder = new LocalBinder();

    //将该接口实现为一个继承Binder得内部类的对象！
    public class LocalBinder extends Binder {
        //在内部类实现一个返回对象的方法
        public SyncService getService() {
            return SyncService.this;
        }
    }

    /**
     * 绑定时执行
     */
    public void onCreate() {
        super.onCreate();
        // Toast.makeText(this,"Service已启动",Toast.LENGTH_SHORT).show();
        //读取shareperf
        SharedPreferences pref = getSharedPreferences("com.hxy.manager_preferences", MODE_PRIVATE);
        Log.i("kkk", "pref" + pref);
        String host2 = pref.getString("ServerUrl", host);
        int port2 = Integer.parseInt(pref.getString("ServerPort", port));
//        用于提示当前service的接口
//        Toast.makeText(getApplicationContext(), host2+":"+port2, Toast.LENGTH_SHORT).show();
        Log.i("kkk", host2 + port2);
    }

    /**
     * 重写onBind方法
     *
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        //  Toast.makeText(this,"本地绑定：SyncService",Toast.LENGTH_SHORT).show();
        return myBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        //  Toast.makeText(this,"取消本地绑定：SyncService",Toast.LENGTH_SHORT).show();
        return false;
    }

    public void uploadData() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                //查询本地数据库数据
                List<GoodsEntity> goodsEntities = GoodsEntityService.listAll(SyncService.this);
                if (goodsEntities!=null){
                    for (GoodsEntity goodsEntity : goodsEntities) {
                        if (goodsEntity!=null&& StringUtil.hasText(goodsEntity.getName())){
                            Log.i("kkk", goodsEntity.getName());
                        }
                    }
                }

//                发送到服务器

                GoodsEntityService goodsEntityService = new GoodsEntityService(SyncService.this);
                goodsEntityService.syncData(SyncService.this, goodsEntities);


                Intent intent = new Intent(Constant.BROADCAST_ACTION);
                intent.putExtra(Constant.MESSAGE, "同步完成");
                sendBroadcast(intent);
            }
        }).start();
    }

}
